﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Rison.BusinessFacade.Common
{
    internal sealed class Encryptor
    {
        private static Encryptor _instance = null;

        private string desKey = "Kevin_Xj";//密钥对
        private string desIV = "Rison_Hh";

        private byte[] desKeys = null;
        private byte[] desIVs = null;

        static Encryptor()
        {
            _instance = new Encryptor();
        }

        private Encryptor()
        {
            desKeys = System.Text.Encoding.Default.GetBytes(desKey);
            desIVs = System.Text.Encoding.Default.GetBytes(desIV);
        }

        public static Encryptor Instance
        {
            get { return _instance; }
        }

        public string Encrypt(string value)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream crypStream = new CryptoStream(memoryStream, des.CreateEncryptor(desKeys, desIVs), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(crypStream);
            sw.Write(value);
            sw.Flush();
            crypStream.FlushFinalBlock();
            memoryStream.Flush();

            return Convert.ToBase64String(memoryStream.GetBuffer(), 0, Convert.ToInt32(memoryStream.Length));
        }

        public string Decrypt(string value)
        {
            try
            {
                if (value != "")
                {
                    byte[] inputValue = Convert.FromBase64String(value);

                    MemoryStream memoryStream = new MemoryStream(inputValue);
                    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                    CryptoStream crypStream = new CryptoStream(memoryStream, des.CreateDecryptor(desKeys, desIVs), CryptoStreamMode.Read);

                    StreamReader sr = new StreamReader(crypStream);
                    return sr.ReadToEnd();
                }
            }
            catch
            {
              
            }

            return "";
        }
    }
}
